实例如下:

复制代码 代码如下:

/**
 * 通过值删除数组元素
 *
 * @param mixed value 元素值
 * @returns array
 */
Array.prototype.deleteValue = function(value){
 var i = 0;
 for(i in this){
  if(this[i] == value) break;
 }
 return this.slice(0, i).concat(this.slice(parseInt(i, 10) + 1));
}

//示例
var test = new Array(1,5,3,4,2);
//输出5
console.log(test.length);
//删除值为4的元素
test = test.deleteValue(4);
//输出[1, 5, 3, 2]
console.log(test);
//输出4
console.log(test.length);

/**
 * 通过索引删除数组元素
 *
 * @param int index 元素索引
 * @returns array
 */
Array.prototype.deleteIndex = function(index){
 return this.slice(0, index).concat(this.slice(parseInt(index, 10) + 1));
}

//示例
var test = new Array(1,5,3,4,2);
//输出5
console.log(test.length);
//删除索引为1的元素
test = test.deleteIndex(1);
//输出[1, 3, 4, 2]
console.log(test);
//输出4
console.log(test.length);

点赞(93)

评论列表共有 0 条评论

立即
投稿
返回
顶部