For some reason, images2 gets set to the same thing as images1 instead of galleryData.splice(0, 3), this is not what I want to happen.
The second console.log(images2) prints what galleryData.splice(0, 3) returns
<script>
export let galleryData
//Logic for organizing images
let showAdditionalImages = false
let images1 = []
let images2 = []
if(galleryData.length >= 3) {
console.log("images2")
console.log(images2)
images1 = galleryData.slice(0, 3)
images2 = galleryData.splice(0, 3)
console.log("images2")
console.log(images2)
console.log("galleryData.splice")
console.log(galleryData.splice(0, 3))
} else {
images1 = galleryData
}
let enlargeBool = false
let enlargedImage
const enlargeImage = (imageData) => {
enlargedImage = {
URL: imageData.URL,
name: imageData.name
}
enlargeBool = true
}
</script>
<main>
<div id="gallery" class="gallery">
<!--Preview for showing the list of images-->
{#each images1 as imageData}
<button on:click={() => {enlargeImage(imageData)}} class="gallery-image">
<span>{imageData.name}</span>
<img src={imageData.URL} alt={imageData.name}/>
</button>
{/each}
{#if images2.length > 0}
{#if showAdditionalImages}
{#each images2 as imageData}
<button on:click={() => {enlargeImage(imageData)}} class="gallery-image">
<span>{imageData.name}</span>
<img src={imageData.URL} alt={imageData.name}/>
</button>
{/each}
{:else}
<button class="load-images" on:click={() => {showAdditionalImages = true}}>Load Additional Images</button>
{/if}
{/if}
<!--Code for the enlarged image when clicked-->
{#if enlargeBool}
<button on:click={() => {enlargeBool = false}} class="enlarged-image">
<div>{enlargedImage.name}</div>
<img src={enlargedImage.URL} alt={enlargedImage.name}/>
</button>
{/if}
</div>
</main>
I tried putting it in an onMount, I tried setting it in a for loop. Idk what this is its crazy to me.
2
Answers
So, turning my computer on the next day and it's fixed... strange occurrence.
The return value of
splice
is not the changed array but an array containing the deleted items, hence why it is the same. Also,splice
modifies an array in place, so this will permanently alter the source array, which may not be what you want.If you just want items after the first three, just use
slice
in both cases.If you really do want to delete the items from the source, it should be rather:
There also is a function
toSpliced
which copies the array, removes items and returns said array, which is probably what you expected here.(But as noted, since this does remove from the start, you could just use
slice(3)
instead.)