JavaScript 中拼接函数的替代方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6515385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:55:21  来源:igfitidea点击:

Alternate method to splice function in JavaScript

javascriptlime

提问by Dayzza

Hi i am working on LIME programming which is a subset of javascript.

嗨,我正在从事 LIME 编程,它是 javascript 的一个子集。

i need to use javascript.splice to remove certain elements from my array, sad to say, LIME does not support splice function.

我需要使用 javascript.splice 从我的数组中删除某些元素,遗憾的是,LIME 不支持 splice 功能。

Any idea how do i create my own function to remove elements from an array?

知道如何创建自己的函数来从数组中删除元素吗?

Thanks for your time.

谢谢你的时间。

EDIT: Manage to create a simple function.

编辑:管理创建一个简单的功能。

function removeElements(array, index)
{
    var tempArray = new Array();
    var counter = 0;

    for(var i = 0; i < array.length; i++)
    {
        if(i != index)
        {
            tempArray[counter] = array[i];
            counter++;
        }
    }
    return tempArray;
}

回答by RobG

Array.prototype.splice is fully defined in ECMA-262 §15.4.4.12, so use that as your spec and write one. e.g.

Array.prototype.splice 在 ECMA-262 §15.4.4.12 中有完整定义,因此将其用作您的规范并编写一个。例如

15.4.4.12 Array.prototype.splice (start, deleteCount [ , item1 [ ,item2 [ , … ] ] ] )

When the splice method is called with two or more arguments start, deleteCountand (optionally) item1, item2, etc., the deleteCountelements of the array starting at array index startare replaced by the arguments item1, item2, etc. An Array object containing the deleted elements (if any) is returned. The following steps are taken:...

15.4.4.12 Array.prototype.splice (start, deleteCount [ , item1 [ ,item2 [ , … ] ] ] )

当使用两个或多个参数startdeleteCount和(可选)item1item2等调用 splice 方法,从数组索引start 开始的数组的 deleteCount元素将替换为参数item1item2等。 Array 对象包含被删除的元素(如果有)被返回。采取以下步骤:...

You will probably have to create a new array, copy the members up to startfrom the old array, insert the new members, then copy from start+ deleteCountto the end to the new array.

您可能必须创建一个新数组,从旧数组开始复制成员,插入新成员,然后从start+ deleteCount复制到新数组的末尾。

Edit

编辑

Here is an amended splice, the first I posted was incorrect. This one splices the array passed in and returns the removed members. It looks a bit long but I tried to keep it close to the spec and not assume support for any complex Array methods or even Math.max/min. It can be simplified quite a bit if they are.

这是一个修改后的拼接,我第一次发布是不正确的。这一个拼接传入的数组并返回删除的成员。它看起来有点长,但我试图让它接近规范,并且不假设支持任何复杂的 Array 方法甚至Math.max/min。如果是的话,它可以简化很多。

If push isn't supported, it can be replaced fairly simply too.

如果不支持推送,也可以相当简单地替换它。

function arraySplice(array, start, deleteCount) {
  var result = [];
  var removed = [];
  var argsLen = arguments.length;
  var arrLen = array.length;
  var i, k;

  // Follow spec more or less
  start = parseInt(start, 10);
  deleteCount = parseInt(deleteCount, 10);

  // Deal with negative start per spec
  // Don't assume support for Math.min/max
  if (start < 0) {
    start = arrLen + start;
    start = (start > 0)? start : 0;
  } else {
    start = (start < arrLen)? start : arrLen;
  }

  // Deal with deleteCount per spec
  if (deleteCount < 0) deleteCount = 0;

  if (deleteCount > (arrLen - start)) {
    deleteCount = arrLen - start;
  }

  // Copy members up to start
  for (i = 0; i < start; i++) {
    result[i] = array[i];
  }

  // Add new elements supplied as args
  for (i = 3; i < argsLen; i++) {
    result.push(arguments[i]);
  }

  // Copy removed items to removed array
  for (i = start; i < start + deleteCount; i++) {
    removed.push(array[i]);
  }

  // Add those after start + deleteCount
  for (i = start + (deleteCount || 0); i < arrLen; i++) {
    result.push(array[i]);
  }

  // Update original array
  array.length = 0;
  i = result.length;
  while (i--) {
    array[i] = result[i];
  }

  // Return array of removed elements
  return removed;
}

回答by Alex Cory

If you don't care about order of the array and you're just looking for a function to perform splice, here's an example.

如果您不关心数组的顺序,而只是在寻找一个函数来执行拼接,这里有一个例子。

/**
 * Time Complexity: O(count) aka: O(1)
 */
function mySplice(array, start, count) {
  if (typeof count == 'undefined') count = 1

  while (count--) {
    var index2remove = start + count
    array[index2remove] = array.pop()
  }

  return array
}

If you want to return the removed elements like the normal splice method does this will work:

如果你想像普通的 splice 方法一样返回被删除的元素,这样做会起作用:

/**
 * Time Complexity: O(count) aka: O(1)
 */
function mySplice(array, index, count) {
  if (typeof count == 'undefined') count = 1

  var removed = []

  while (count--) {
    var index2remove = index + count
    removed.push(array[index2remove])
    array[index2remove] = array.pop()
  }
  // for (var i = index; i < index + count; i++) {
  //    removed.push(array[i])
  //    array[i] = array.pop()
  // }

  return removed
}

回答by viclm

Here is a simple implement in case the Array.prototype.splice dispears

这是一个简单的实现,以防 Array.prototype.splice 消失

if (typeof Array.prototype.splice === 'undefined') {
    Array.prototype.splice = function (index, howmany, elemes) {
        howmany = typeof howmany === 'undefined' || this.length;
        var elems = Array.prototype.slice.call(arguments, 2), newArr = this.slice(0, index), last = this.slice(index + howmany);
        newArr =  newArr.concat.apply(newArr, elems);
        newArr =  newArr.concat.apply(newArr, last);
        return newArr;
    }
}

回答by user113716

This modifies the original Array, and returns the items that were removed, just like the original.

这会修改原始数组,并返回已删除的项目,就像原始数组一样。

Array.prototype.newSplice = function( start, toRemove, insert ) {
    var remove = this.slice( start, start + toRemove );
    var temp = this.slice(0,start).concat( insert, this.slice( start + toRemove ) );
    this.length = 0;
    this.push.apply( this, temp );
    return remove;
};

Comparison test:http://jsfiddle.net/wxGDd/

对比测试:http : //jsfiddle.net/wxGDd/

var arr = [0,1,2,3,4,5,6,7,8];
var arr2 = [0,1,2,3,4,5,6,7,8];


console.log( arr.splice( 3, 2, 6 ) );      // [3, 4]
console.log( arr );      // [0, 1, 2, 6, 5, 6, 7, 8]

console.log( arr2.newSplice( 3, 2, 6 ) );  // [3, 4]
console.log( arr2 );     // [0, 1, 2, 6, 5, 6, 7, 8]

It could use a little extra detail work, but for the most part it takes care of it.

它可以使用一些额外的细节工作,但在大多数情况下它会照顾它。

回答by Prem

I have used this below functionas an alternative for splice()

我在下面使用它function作为替代splice()

array = mySplice(array,index,count);

above is the function call, And this is my function mySplice()

上面是函数调用,这是我的函数 mySplice()

 function mySplice(array, index, count)
{    
    var newArray = [];
    if( count > 0 ) 
        { count--;}
    else
        { count++;}
    for(i = 0; i <array.length; i++)
        {
            if(!((i <= index + count && i >=  index) || (i <= index && i >=  index + count)))  
            {
               newArray.push(array[i])
            }            
        }      
    return newArray;
}

回答by macha devendher

I have done it very similar way using only one for loop

我仅使用一个 for 循环就以非常相似的方式完成了

function removeElements(a,index,n){
  // a=> Array , index=> index value from array to delete
 // n=> number of elements you want to delete
   let temp = []; // for storing deleted elements
   let main_array = []; // for remaining elements which are not deleted
   let k = 0;
   for(let i=0;i<a.length;i++){
      if((i===index) || ((index<i && i<n+index))){
      temp[i]=a[i+1];
      delete a[i];
       }
    if(a[i]!==undefined){
      main_array[k] = a[i]; 
      a[i] = main_array[k];
       k++;
       }
     }

      a=main_array;
   return a;
   }
  a=[1,2,3,4,5];
  console.log(removeElements(a,0,1));

follow link Jsfiddle

按照链接Jsfiddle

回答by Percy

Are there any other methods that are missing in LIME's Array implementation?

LIME 的 Array 实现中是否还缺少其他任何方法?

Assuming at least the most basic push()and indexOf()is available, there's several ways you could do it. How this is done would depend on whether this is destructive method or whether it should return a new array. Assuming the same input as the standard splice(index, howMany, element1, elementN)method:

假设至少是最基本的push()并且indexOf()可用,有几种方法可以做到。如何做到这一点取决于这是一种破坏性方法还是它是否应该返回一个新数组。假设输入与标准splice(index, howMany, element1, elementN)方法相同:

  1. Create a new array named new
  2. push()indexes 0 to indexonto the newarray
  3. Now stop at indexand push()any new elements passed in. If LIME supports the standard argumentsvariable then you can loop through argumentswith index > 2. Otherwise you'll need to pass in an array instead of a variable number of parameters.
  4. After inserting the new objects, continue looping through the input array's elements, starting at index + howManyand going until input.length
  1. 创建一个名为的新数组 new
  2. push()索引 0indexnew数组
  3. 现在停止indexpush()传入任何新元素。如果 LIME 支持标准arguments变量,那么您可以arguments使用索引 > 2循环。否则,您将需要传入一个数组而不是可变数量的参数。
  4. 插入新对象后,继续遍历输入数组的元素,从 atindex + howMany开始直到input.length

I believe that should get you the results you're looking for.

我相信这应该会让你得到你想要的结果。