【问题标题】:Append Javascript arrays or object like python附加 Javascript 数组或对象,如 python
【发布时间】:2018-05-15 10:35:53
【问题描述】:

我尝试了不同的东西,比如数组推送和新的 Set() .add,但我无法实现像 python 附加这样的功能。有什么想法吗?我错过了什么吗?

ex. in py
x = [1, 2, 3]
x.append([4, 5])
gives you: [1, 2, 3, [4, 5]]

如果我在一个 for 循环中并且我附加到第一项

item.append(9)

给你:[[1, 9], 2, 3]

第二个是我想在 2 个 for 循环中使用的那个

js ex
let b = [1,2,3];
b.forEach(function (item) {
  item.push(9); //error
});

也许这是一个愚蠢的问题,但我是 js 的新手,抱歉:S

【问题讨论】:

  • 鉴于x = [1, 2, 3]for n in x: n.append(9) 在 Python 中无论如何都会失败。
  • 是这样的。我有一个数组 [1,2,3] 并且在一个 foreach 中,如果匹配的案例我想在里面附加一个 9。例如 [[1,9],2,3]
  • 什么情况下?什么情况?请将信息添加到问题中

标签: javascript python arrays append


【解决方案1】:

最简单的方法是Iterable Spread syntax

const x = [1, 2, 3];
const y = [...x, [4, 5]];

console.log(x);
console.log(y);

你也可以使用Array.prototype.push

const x = [1, 2, 3]
x.push([1, 2]);

console.log(x);

【讨论】:

    【解决方案2】:
    var a = [1,2,3,4,5];
    a.push(#here you can enter the content that you want to add to your array)
    #if content is more than 1 then add inside []
    document.write(a)
    

    【讨论】:

    • 好的,它以愚蠢的方式工作,我将初始化数据转换为数组 let b = [[1],[2],[3]];谢谢!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    相关资源
    最近更新 更多