简体   繁体   English

从 JavaScript 中的数组初始化变量

[英]Initializing varibles from array in JavaScript

I want to declare and assign default values to variables我想为变量声明和分配默认值

let country, state, fruits;
let checkBoxfields = ['country', 'state', 'fruits'];
checkBoxfields.forEach(field=>{
    if(some condition){
        return field = true;
    }else{
        field = false;
    }

I want final output as such我想要最终的 output 这样

country = true;
state = false;
fruits = true;

You can create an empty object and then iterate over the checkBoxFields and then populate the object as needed您可以创建一个空的 object,然后遍历checkBoxFields ,然后根据需要填充 object

const obj = {};

const checkBoxfields = ['country', 'state', 'fruits'];
checkBoxfields.forEach(field => {
    if (some condition) {
        obj[field] = true;
    } else {
        obj[field] = false;
    }
});

Sample output样品 output

console.log(obj); // {country: false, state: true, fruits: true}

If the structure is consistent and value are always in the same order, then you can map and destructure value in variable with desired name something like this如果结构一致并且值始终处于相同的顺序,那么您可以 map 并在具有所需名称的变量中解构值,如下所示

 let checkBoxfields = ['country', 'state', 'fruits']; let [country, state, fruits] = checkBoxfields.map(field => { return field === 'country' || field === 'fruits' }) console.log(country, state, fruits)


If the variables are defined in global scope you can use window to reference variable, That being said you should avoid using global as much as possible it has it's own drawback, makes code so hard to debug如果变量是在全局 scope 中定义的,您可以使用 window 来引用变量,也就是说您应该尽可能避免使用全局,它有它自己的缺点,使代码很难调试

 var country, state, fruits; const checkBoxfields = ['country', 'state', 'fruits']; checkBoxfields.forEach(field => { if (field === 'country' || field === 'fruits') { window[field] = true; } else { window[field] = false; } }); console.log(country,state,fruits)

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

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