简体   繁体   中英

javascript how insert "empty" to array?

 var array = new Array(5); array[0] = 1; array[1] = 1; array[3] = 1; array[4] = 1; console.log(array.hasOwnProperty(0)); //true console.log(array.hasOwnProperty(1)); //true console.log(array.hasOwnProperty(2)); //false console.log(array.hasOwnProperty(3)); //true console.log(array.hasOwnProperty(4)); //true

I want to insert array that have unsetted element.

 var array = [1,1] var arrayToInsert = new Array(3); arrayToInsert[0] = 1; arrayToInsert[2] = 1; array.splice(1, 0, ...arrayToInsert); console.log(array.hasOwnProperty(0)); //true console.log(array.hasOwnProperty(1)); //true console.log(array.hasOwnProperty(2)); //true, I want to make it false. console.log(array.hasOwnProperty(3)); //true console.log(array.hasOwnProperty(4)); //true

How keep unsetted element after I splice(insert) array that have unsetted element?

Not sure to understand your question, but if you want to unset a value from your array (so, setting it as undefined), you can delete the array element:

 const a = [1, 2, 3, 4]; console.log(a); delete(a[2]); console.log(a);

If you want to insert a value meaning "empty" into an array, simply assign the special value of undefined to your chosen position in the array.

 var array = ['a','b', 'c', 'd', 'e'] var arrayToInsert = ['🍿', undefined, '⛱'] array.splice(1, 0, ...arrayToInsert) console.log(array) console.log(Object.keys(array)) console.log(array.length)

When you see the word "empty" written in the console, is used by Chrome to indicate the absence of a property corresponding to an index.

Note that the printing of the word "empty" to the console is a peculiarity of Chrome and is not part of the JavaScript standard.

To remove one of the index properties from an array, you use the delete keyword.

Note how doing so looks different in the consoles of Chrome, Safari and Firefox:

铬合金 苹果浏览器 火狐

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