在这种情况下,为什么要对原件进行分类修改? [英] Why is sorting modifing the original in this case?

查看:98
本文介绍了在这种情况下,为什么要对原件进行分类修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,那就是要更改原始数组,奇怪的是,添加arr.join("...").split("...")似乎可以防止这种情况:

I had a problem that was making the original array to change, the curious thing is that adding arr.join("...").split("...") seems to prevent this:

一些背景:

  • 我的脚本创建并向array
  • 添加内容
  • 此数组初始化为空,如arr=[]
  • 事物通过arr[index] = "..."
  • 添加
  • 然后我想复制一份arr但已排序的
  • 当我进行排序时,原始的arr被修改
  • my script creates and adds stuff to an array
  • this array initialized empty like arr=[]
  • the things are added passing arr[index] = "..."
  • then I want to have a copy of the arr but sorted
  • when I do the sorting, the orignial arr is modified

这是正在发生的事情的简化版本:

Here is a simplified version of what is going on:

var arr=[], sorted;

arr[0] = "hello";
arr[1] = "world";

//buggy, the original is sorted
//sorted = arr.sort(function(a,b){return (a.length-b.length);});

sorted = arr.join("improbableCollision").split("improbableCollision").sort(function(a,b){return (a.length-b.length);});

  • 为什么添加.join("*").split("*")可以解决问题?
  • 是什么原因引起的问题?
  • 是否有更优雅的方法来解决此问题?
    • Why adding .join("*").split("*") solves the problem?
    • What was causing the problem?
    • Is there a more elegant way to fix this?
    • 有关完整脚本,请检查此 jsFiddle

      For the full script, check this jsFiddle

      推荐答案

      要在不进行所有合并和拆分的情况下进行排序,请使用slice或concat复制数组:

      To sort without all that joining and splitting, copy the array with slice or concat:

      var sorted = arr.slice(0).sort()

      var sorted = arr.slice(0).sort()

      这篇关于在这种情况下,为什么要对原件进行分类修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆