繁体   English   中英

从数组JavaScript中提取元素

[英]Extract elements from array javascript

我对javascript完全陌生,所以请多多包涵!

我有一个函数,将变量传递给它,如下所示:

function.getDestination(
    {
      destinations: [theFirstDestination, theSecondDestination],
    }

通过显式定义它们,我可以传递尽可能多的变量。 我还有一个数组,其中包含要传递的值destinationArray 同样,我可以通过从数组中显式调用它们来传递这些变量:

function.getDestination(
    {
      destinations: [destinationArray[0], destinationArray[1],
    }

我想做的是遍历整个数组并将每个变量传递给函数:有没有比手动键入每个索引更简单的方法呢?

您可以执行destinations: destinationArray如果您愿意),但是一侧的更改会影响另一侧。 如果您想要完全独立的副本:

destinations: destinationArray.slice(0)

我认为您要尝试将数组复制到destinations 在这种情况下,只需使用:

{
     destinations: destinationArray.slice(0)
}

代码未经测试(现在无法测试),但应该可以工作。

function getDestination(param) {
    for(var i=0;i<param.destinations.length;i++) {

        // do something with i (the number)
        // or with param.destinations[i] (the value)

        console.log(i+": "+param.destinations[i]);
    }
}

虽然这也适用于对象

function getDestination(param) {
    for(var it in param.destinations) if(param.destinations.hasOwnProperty(it)) {

        // do something with it (the number or key)
        // or with param.destinations[it] (the value)

        console.log(it+": "+param.destinations[it]);
    }
}

您这样称呼其中之一:

getDestination({destinations: [theFirstDestination, theSecondDestination]});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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