【问题标题】:Send only Selected array data to another array using Javascript使用 Javascript 仅将选定的数组数据发送到另一个数组
【发布时间】:2018-11-14 07:15:30
【问题描述】:

我有一个包含以下数据的 JSON 数组

source=[{"OperationName":"All","PrivilegeName":"Roles CRUD"},
        {"OperationName":"Read","PrivilegeName":"Roles Read Delete"},
        {"OperationName":"Delete","PrivilegeName":"Roles Read Delete"},
        {"OperationName":"Read","PrivilegeName":"Roles Update"},
        {"OperationName":"Update","PrivilegeName":"Roles Update"}]

我有一个目标数组,即destination =[];

我创建了一个函数 bindRowEvent(),它从表中返回选定的行并将其保存到变量 _currentSelectedRow

我正在尝试选择特定行并仅将所选值发送到目标数组。 我可以为第一个值执行此操作,但是在第二次调用该函数时,它只会覆盖目标中的第一个值

function AssignOne(_currentSelectedRow) {
         debugger;
         //destination.push(_currentSelectedRow);

         if (destination.length == 0) {
              destination = source.slice(_currentSelectedRow, 1);
         }
         else {                                 
              destination = source.slice(_currentSelectedRow, destination.length+1);

         }

         source.splice(_currentSelectedRow, 1);
         console.log(destination);

         displaySource();
         displayDestination2();
         bindRowEvent();
 }

我该如何解决这个问题?

【问题讨论】:

  • destination.push() 不起作用?
  • 你能从你的代码中创建一个小提琴吗?

标签: javascript jquery arrays json ajax


【解决方案1】:

正如您所注意到的,您的代码会工作一点,但仅当您第一次运行它时_currentSelectedRow0。演示:http://jsfiddle.net/6hqn7xs5/1/。这是因为在“切片”调用中,您始终将“结束”参数指定为 1。As per the documentation 这意味着返回的数组将仅包含索引 1 之前的内容。反过来,这意味着如果您为“开始”参数指定任何大于 0 的数字,则为切片指定的范围不能选择任何项目。您必须动态指定“end”,因为它总是比“begin”大一。

其次,它每次都覆盖整个目标的原因是= 运算符将destination 变量的值重新分配给新给定的值。它不会添加任何东西。这是 JavaScript(和大多数编程语言)的一个非常基本的概念,您需要确保自己理解。

但是,由于您只想选择一项,因此上面的所有内容都是多余的。通过索引选择单个项目然后使用push() 以(有充分记录的)方式将其添加到数组中是微不足道的:

var source = [{
    "OperationName": "All",
    "PrivilegeName": "Roles CRUD"
  },
  {
    "OperationName": "Read",
    "PrivilegeName": "Roles Read Delete"
  },
  {
    "OperationName": "Delete",
    "PrivilegeName": "Roles Read Delete"
  },
  {
    "OperationName": "Read",
    "PrivilegeName": "Roles Update"
  },
  {
    "OperationName": "Update",
    "PrivilegeName": "Roles Update"
  }
];
var destination = [];

function AssignOne(_currentSelectedRow) {
  destination.push(source[_currentSelectedRow]);

  console.log(destination);

  /*displaySource();
  displayDestination2();
  bindRowEvent();*/
}

AssignOne(0);
AssignOne(2);

附:我会温和地建议您阅读JavaScript arraysJavaScript assignment operators 的基础知识,这样您以后就不会犯此类错误了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 2021-07-04
    • 2020-08-23
    • 2021-12-31
    • 1970-01-01
    • 2017-06-22
    • 2019-01-28
    • 1970-01-01
    相关资源
    最近更新 更多