如何循环数组

How to loop array

本文关键字:数组 循环 何循环      更新时间:2024-03-02

我试图将一个对象添加到JavaScript数组中,然后循环它。但循环没有运行

    var basicConf = {
    RootUrl: "https://api.joltcomm.com/",
    username: 'test',
    password: 'test',
    APPURL:'https://dev.joltcomm.com/secureadmin/',
    PROJECTID:'',
    uData:'',
    iFunc:[],
    pushData:function(data){
        this.iFunc.push(data);
    }
    };
    function onProjectLoad(fn,params)
    {
        basicConf.pushData({'function':fn,'parameters':params});
    }
    onProjectLoad("getData",["user-project/2","showProjects",1]);
    $.each(basicConf.iFunc, function( index, value ) {
        console.log(value);
    var fn=value.function+'(';
        $.each(value.parameters, function( i, v ) {
            if(i>0)
            {
                fn+=',';
            }
            fn+='"'+v+'"';
        });
        fn+=');';
        console.log(fn);
       eval(fn);
    });

我没有进入循环,我不知道为什么

很难将项目推送到对象。

iFunc:{},  <-- object

如果你真的想把它们添加到一个数组中,你就需要一个数组。

iFunc:[],   //<-- That is an array, you can push to the array

如果你只是想更新对象,不要使用推送。


var basicConf = {
    RootUrl: "https://api.example.com/",
    username: 'test',
    password: 'test',
    APPURL:'https://dev.example.com/example/',
    PROJECTID:'',
    uData:'',
    iFunc:[],
    pushData:function(data){
        this.iFunc.push(data);
        console.log(this.iFunc)
    }
};
function onProjectLoad(fn,params)
{
    basicConf.pushData({'function':fn,'parameters':params});
}
onProjectLoad("getData",["user-project/2","showProjects",1]);

push是一个数组方法,您不能将新事物"推送"到对象中,因为您需要提供一个键来存储数据。

addData:function(data){
  this.iFunc.someKey = data;
}

实际上,你不能直接在对象上按下key/val,但你可以用数组方式设置它们:

var basicConf = {
    RootUrl: "https://api.example.com/",
    username: 'test',
    password: 'test',
    APPURL:'https://dev.example.com/example/',
    PROJECTID:'',
    uData:'',
    iFunc:{},
    pushData:function(data){
        for (key in data) {
            this.iFunc[key] = data[key];
        }
    }
};
function onProjectLoad(fn,params)
{
    basicConf.pushData({'function':fn,'parameters':params});
}
onProjectLoad("getData",["user-project/2","showProjects",1]);

因此,如果你console.log你的basicConf,它会像:

iFunc: Object
function: "getData"
parameters: Array[3]
    0: "user-project/2"
    1: "showProjects"
    2: 1

我认为这正是您所需要的。用附加值扩展现有对象的方法。

var basicConf = {
  RootUrl: "https://api.example.com/",
  username: 'test',
  password: 'test',
  APPURL: 'https://dev.example.com/example/',
  PROJECTID: '',
  uData: '',
  iFunc: {},
  pushData: function(data) {
    this.iFunc.push(data);
  }
};
function onProjectLoad(fn, params) {
  extend(basicConf, {
    'function': fn,
    'parameters': params
  });
}
onProjectLoad("getData", ["user-project/2", "showProjects", 1]);
function extend(dest, src) {
  var keys = Object.keys(src);
  var i = 0;
  while (i < keys.length) {
    if (!this.extend || (this.extend && dest[keys[i]] === undefined)) {
      dest[keys[i]] = src[keys[i]];
    }
    i++;
  }
  return dest;
}