【学习】检测数组、重排序方法

1.可以用type of 来检测每个属性是否存在

2.数组的 length 属性不是只读的 ,因此通过这个属性 ,可以从数组的末尾移除项或向数组中添加新项

eg: 移除

var colors = ["red", "yellow", "grown"];

colors.length = 2;

alert(colors.length)     // undefined 

 eg:新增

var colors = ["red", "yellow", "grown"];

colors[colors.length] = "#338bff";

alert(colors)      //["red", "yellow", "grown", "#338bff"]

eg:特定位置新增

var colors = ["red", "yellow", "grown"];

colors[9] = "#338bff";

console.log(colors)     //["red", "yellow", "grown", empty × 6, "#338bff"]

console.log(colors.length )  // 10

 3.sort 用法

eg:

var values = [10, 5, 1, 15 ,8]
function compare(val1, val2) {
  if (val1 < val2) {
      return -1   //如果降序这个取反
  } else if (val1, val2) {
      return 1 
  } else {   // 如果降序这里取反
      return 0
  }
}
values.sort(compare)
document.write(values) // [1,5,8,10,15]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值