如何在 JavaScript 中将对象(例如字符串或数字)附加到数组中?
技术问答
399 人阅读
|
0 人回复
|
2023-09-12
|
如何在 JavaScript 将对象(如字符串或数字)附加到数组中?
" |6 v& H7 n+ T4 W$ i# s6 z7 d& k* v& F! U
! u$ \5 H& z% b1 s& |. r 解决方案:
" z4 T3 N$ O c- ]6 K 使用该Array.prototype.push该方法将值附加到数组的末尾:7 c# Y* E! y) P' |8 P, |& |
// initialize arrayvar arr = [ "Hi", "Hello", "Bonjour"];// append new value to the arrayarr.push("Hola");console.log(arr);+ i: Y, D; X6 o
你可以用这个push()函数在一次调用中将多个值附加到数组中:
2 T3 l9 o% E$ f7 {+ i1 z: X2 [ j
3 k% T. v2 V" V6 M9 W! H' y- // initialize arrayvar arr = ["Hi","Hello","Bonjour","Hola"];// append multiple values to the arrayarr.push("Salut","Hey");// display all valuesfor (var i = 0; i 更新
# a& n" L- \1 y3 W - 如果要向另一个数组添加一个数组项目,可以使用firstArray.concat(secondArray):[code]var arr = [ "apple", "banana", "cherry"];// Do not forget to assign the result as,unlike push,concat does not change the existing arrayarr = arr.concat([ "dragonfruit", "elderberry", "fig"]);console.log(arr);) d C9 e0 I) F, r" U: Z
更新' d# S. u, r; Y+ j
如果您想在数组开头(即第一个索引)添加任何值,可以Array.prototype.unshift用于此目的。: W+ q- h, Z" R' l3 v$ I
var arr = [1,2,3];arr.unshift(0);console.log(arr);4 B( W2 k- O1 T1 ~5 w; g6 b4 m
它还支持一次附加多个值,就像push.
' l( A8 A% Q& J3 h2 `更新6 j1 q p2 V/ y: C- I
ES6语法的另一种方法是使用扩展语法返回新数组。这使得原始数组保持不变,但返回新数组,符合函数编程的精神。
2 E* C7 [, D g c8 p/ Econst arr = [ "Hi", "Hello", "Bonjour",];const newArr = [ ...arr, "Salut",];console.log(newArr);% i+ m2 X. d/ {8 s9 [4 a, n* R0 V$ g
|
|
|
|
|
|