拼接在三元条件下不起作用

时间:2018-01-25 04:38:33

标签: javascript

尝试删除两个数组中出现的任何数字:

function diff(args) {

  var diff = [].concat.apply([],arguments).reduce(
    function(result, current) {

      console.log("result: " + result);
      console.log("current: " + current);
      console.log("result.indexOf(current): " + result.indexOf(current));

      return result.indexOf(current) === -1 
      ? result.concat(current) 
      : result.splice(result.indexOf(current), 1);
    }, []
  );
  console.log("diff: " + diff); 
  return diff;
}

console.clear();
diff([1, 2, 3], [5, 2, 1, 4]);

然而,控制台表明:

Console was cleared
result: 
current: 1
result.indexOf(current): -1
result: 1
current: 2
result.indexOf(current): -1
result: 1,2
current: 3
result.indexOf(current): -1
result: 1,2,3
current: 5
result.indexOf(current): -1
result: 1,2,3,5
current: 2
result.indexOf(current): 1
result: 2
current: 1
result.indexOf(current): -1
result: 2,1
current: 4
result.indexOf(current): -1
diff: 2,1,4

为什么要忽略slice语句,而是使用当前的var?

重置我的结果var

理想情况下,我认为第一次查找的result.splice(result.indexOf(current),1)会导致:

1,3,5

不是

2

2 个答案:

答案 0 :(得分:1)

Array#splice returns已移除的数组切片,您将其分配给结果。

您应该使用Array#slice代替:



function diff(args) {

  var diff = [].concat.apply([], arguments).reduce(
    function(result, current) {

      console.log("result: " + result);
      console.log("current: " + current);
      console.log("result.indexOf(current): " + result.indexOf(current));
      
      var index = result.indexOf(current);

      return index === -1 ?
        result.concat(current) :
        result.slice(0, index).concat(result.slice(index + 1));
    }, []
  );
  console.log("diff: " + diff);
  return diff;
}

console.clear();
diff([1, 2, 3], [5, 2, 1, 4]);




答案 1 :(得分:0)

现在是splice的预期行为,其中......

  

返回值:包含已删除元素的数组

我们可以更好地看到我们将这个三元交换为if。这就是你现在拥有的:

if (result.indexOf(current) === -1) {
    return result.concat(current)
} else {
    return result.splice(result.indexOf(current), 1);
}

因此,正如您所看到的,您将返回已删除的元素。

你想要的是这个:

if (result.indexOf(current) === -1) {
    return result.concat(current)
} else {
    result.splice(result.indexOf(current), 1);
    return result
}

现在,您将删除该元素,并且仅在返回结果数组后才会删除。

以下是您更改的代码:



function diff(args) {
  var diff = [].concat.apply([], arguments).reduce(
    function(result, current) {

      console.log("result: " + result);
      console.log("current: " + current);
      console.log("result.indexOf(current): " + result.indexOf(current));

      if (result.indexOf(current) === -1) {
        return result.concat(current)
      } else {
        result.splice(result.indexOf(current), 1);
        return result
      }
    }, []
  );
  console.log("diff: " + diff);
  return diff;
}

console.clear();
diff([1, 2, 3], [5, 2, 1, 4]);