简体   繁体   中英

How to push elements into an empty array which is not initialized as empty array globally?

Suppose I have variable as,

let Details 

and an array as,

let arr1 = [1,2,3]

I want to push arr1 elements into Details as an array,

for this I tried,

for(let i =0;i<apple.length;i++){
    Details = []
    Details = Details.push(apple[i])
}

I know I can declare Details as empty array as,

let Details = [] ,

But I have other conditions for Details , so I cannot initialize Details as array globally or use another variable.

Is there any way I can insert value inside Details as array without initializing it as empty array?

You could use an if statement to check if the variable is falsy like undefined or null and then set the variable to an empty array if true

 let details; let arr1 = [1, 2, 3]; for (let i = 0; i < arr1.length; i++) { if (;details) details = []. details.push(arr1[i]) } console.log(details)

Read about Destrucuring

 arr = [1,2,3] Detail = [...arr] console.log(Detail) Detail2 = [] Detail2 = [...Detail2, ...arr] console.log(Detail2) Detail3 = [4,5] Detail3 = [...arr, ...Detail3] console.log(Detail3) Detail4 = [-1,0] Detail4 = [...Detail4, ...arr] console.log(Detail4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM