按条件将动态参数添加到Javascript数组对象

时间:2016-03-09 14:21:43

标签: javascript arrays

我想将parameter添加到array object url取决于某些函数值。

这是我到目前为止没有运气的尝试。

var change_lookup_number = function() {
  var type = document.getElementById('type_number').value;
  if (type == 1) {
    //url should be "/hello/lookup/modelname.js?columns[column_id]=1"
  } else if (type == 2) {
    //url should be "/hello/lookup/modelname.js?columns[column_id]=2"
  } else {
    //url should be "/hello/lookup/modelname.js?columns[column_id]=6"
  }
};

change_lookup_number();

var sections = [
  {
    url: "",
  }
]

(function(){
  $.each(pcdfs, function(i, section) {
   console.log(section.url); // It's empty, I want to change this section.url
  }
})();

由于

1 个答案:

答案 0 :(得分:0)

Define sections array before accessing it inside your function.

var sections = [
      {
        url: ""
      }
    ];
var change_lookup_number = function() {
      var type = document.getElementById('type_number').value;
      if (type == 1) {
        sections[0].url = "/hello/lookup/modelname.js?columns[column_id]=1"
      } else {
        sections[0].url = "/hello/lookup/modelname.js?columns[column_id]=2"
      }
    };

change_lookup_number();