如何设置全局数组

时间:2016-05-04 18:31:30

标签: javascript arrays

我有一个JavaScript函数,类似于

function ColorListPicker(listLength) {
    var colorCodeArray = ["#046c93", "#4caf50", "#8bc34a", "#cddc39", "#00bcd4", "#009688", "#e91e63", "#673ab7", "#ff9800", "#9e9e9e", "#f3f3f3"];
    var colorList = "[";
    for (var i = 0; i < listLength; i++) {
        colorList = colorList + '"' + colorCodeArray[i] + '",';
    }
    var colorListData = colorList.substr(0, colorList.length – 1);
    colorListData = colorListData + "]";
    return colorListData;
}

如果我正常调用此函数,例如var colorList = ColorListPicker(5);,那么colorList变量将设置为返回值,就好像我已完成colorList=["#046c93", "#4caf50", "#8bc34a", "#cddc39", "#00bcd4"]

但我想声明colorCodeArray是全局的,并从我的ColorListPicker函数中使用它。

如何让ColorListPicker设置全局变量,而不是返回值?

2 个答案:

答案 0 :(得分:2)

  

但现在我想声明colorCodeArray变量global并从我的ColorListPicker函数中使用它。

只需将数组提取到全局变量中,然后在函数中使用它:

var colorCodeArray = ["#046c93", "#4caf50", "#8bc34a", "#cddc39", "#00bcd4", "#009688", "#e91e63", "#673ab7", "#ff9800", "#9e9e9e", "#f3f3f3"];  

function ColorListPicker(listLength) {

  // use colorCodeArray within the function

}

相关问题:What is the scope of variables in JS

查看the answer by Rion Williams以获取有关改善功能的其他有用建议

答案 1 :(得分:1)

确定适当的范围

只需考虑将colorCodeArray变量声明在ColorListPicker()函数范围之外,这将使其作为全局变量起作用:

// Now colorCodeArray should be accessible from anywhere you need it
var colorCodeArray = ["#046c93", "#4caf50", "#8bc34a", "#cddc39", "#00bcd4", "#009688", "#e91e63", "#673ab7", "#ff9800", "#9e9e9e", "#f3f3f3"];  

// Define your function here
function ColorListPicker(listLength){
    // Your code here
}

考虑使用slice()代替循环

此外,您似乎正在尝试检索数组的前N个元素。如果是这种情况,您可以考虑使用slice()函数来执行此操作:

function ColorListPicker(listLength){
     // This would return the first N elements from your global array
     return colorCodeArray.slice(0,listLength);
}

如果您想构建字符串,请使用join()

或者如果你想用方括号显式地包装结果,你可以使用join()函数使用特定的分隔符将数组的元素合并为一个字符串:

function ColorListPickerAsString(listLength){
    // This would return "['#046c93','#4caf50','#8bc34a','#cddc39','#00bcd4']"
    return '[\'' + colorCodeArray.slice(0,listLength).join('\',\'') + '\']';
}

示例

你可以see an example of both of these options here并在下面演示:

enter image description here