javascript - 如何将一个数组插入另一个数组?

标签 javascript jquery angularjs html angularjs-directive

我有一个包含 64 个位置的主数组,对于每个位置我都需要另一个数组。例如:someArray[index] = [someObject]

我如何创建这些数组?以及如何获取 someObject.name 、 someObject.lastName

这是代码:

$scope.filaCores = []; 
$scope.object = {} 
$scope.object.name = "name"; 
$scope.object.secondname= "secondname"; 
for(var i = 0; i <10; i++) { 
   $scope.filaCores[i] = [$scope.object.name, $scope.object.secondname]; 
} 

最佳答案

给你: https://jsfiddle.net/jsg81gg8/1/

根据您的描述,我认为不需要数组数组。但既然这就是你所要求的,那就去吧。您没有指定子数组有多少个数组元素,因此我将展示一个包含三个元素的示例。如果总共只需要 64 个结构,则不需要内部数组。

window.getRandomInt = function() {
    return Math.floor(Math.random() * (10000 - 1 + 1)) + 1;
}

mainArray = [];  /* you said you wanted 64 of these */
subArray = [];  /* you didn't specify how many of these, the example below will assume 3 per each mainarray */

for (i = 0; i < 64; i++) {
    for (j = 0; j < 3; j++) {
        /* I'm using getRandomInt() just so you can see all the names are different */
        subArray[j] = {name:"John"+getRandomInt(), lastname:"Doe"+getRandomInt()};
        }
    mainArray[i] = subArray;
}

/* Press F12 and go to the console tab, run this script, and you will see the output of the entire array */
console.log(mainArray);

/* You can access a specific element like this... */
alert('Alerting mainArray[23][2].lastname: '+mainArray[23][2].lastname);

如果你确实不需要子数组,并且只需要 64 个结构,那么它可以简化为如下所示: https://jsfiddle.net/Ldafbwbk/1/

更新:这是第三个示例,更接近您更新的问题: https://jsfiddle.net/7st8fnw5/3/

关于javascript - 如何将一个数组插入另一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36438314/

相关文章:

javascript - 以正确的方式导入/注入(inject) TypeScript+AngularJS 模块

javascript - 在 JS 中对数字文字调用函数的规则是什么?

javascript - 在 Javascript (node.js) 中的 1, 4, 7... 处插入 div.row

javascript - jquery 输入字段聚焦除 div

javascript - 如何使用 Protractor 验证不同位置的两个跨度是否相等?

javascript - 仅在用户第一次在表单输入中键入时运行函数

javascript - Windows Phone 8.1 WinJS Appbar 禁用属性不起作用

javascript - Three.js object3d.translateZ 导致所有位置值均为 NaN

javascript - 如何获取列表内的 anchor 标记的标题并选择类

javascript - $(window).on ("load") 在 postRender 中未触发