JS数组的高级使用方法 JS数组的高级使用方法示例小结

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JS数组的高级使用方法 JS数组的高级使用方法示例小结

jadeshu   2021-04-21 我要评论

本文实例讲述了JS数组的高级使用方法。分享给大家供大家参考,具体如下:

//数组的高级使用
 
var array = [10,12,20,30];
 
for(var index in array){
 console.log(array[index]);
}
 
//length 数组长度
 
for(var i = 0; i < array.length; i++){
 console.log(array[i]);
}
 
//数组添加新数据
 
array.push(1000);
 
array.push(2000);
 
array.push("hello world");
 
array.push({key:"jadeshu"});
 
console.log(array); //[10, 12, 20, 30, 1000, 2000, "hello world", {key:"jadeshu"}]
 
//数组删除最后一个数据
 
array.pop();
 
console.log(array); // [10, 12, 20, 30, 1000, 2000, "hello world"]
 
//查找数组里面值的索引
 
var idex = array.indexOf(2000);
 
console.log(idex); //5
 
//数组删除
 
//splice(开始索引,索引之后的个数)
 
var data = array.splice(2,3);
 
console.log(data); //[20, 30, 1000]
 
console.log(array); //[10, 12, 2000, "hello world"]

1.给定一个数组,让元素按照从大到小,从小到大排序

var array_num = [12,12,13,564,7,55,66];
 
//从小到大排序
 
array_num.sort(function (lhs,rhs) {
 
 if (lhs < rhs){
  return -1;
 }else if(lhs > rhs) {
  return 1;
 }else {
  return 0;
 }
})
 
console.log(array_num) // [7, 12, 12, 13, 55, 66, 564]
 
console.log("=======================");
 
array_num = [12,12,13,564,7,55,66];
 
//从大到小排序
 
array_num.sort(function (lhs,rhs) {
 
 if (lhs < rhs){
  return 1;
 }else if(lhs > rhs) {
  return -1;
 }else {
 return 0;
}
 
});
 
console.log(array_num) //[564, 66, 55, 13, 12, 12, 7]
 
console.log("=======================");

2.随机打乱一个数组

array_num = [12,12,13,564,7,55,66];
 
array_num.sort(function () {
 
 if ( Math.random() < 0.5){
  return -1;
 }else {
  return 1;
 }
});
 
console.log(array_num); //[12, 12, 564, 13, 7, 66, 55] 随机
 
console.log("=======================");

3.编写程序 随机的生存[10,100)范围内的整数

function random_int_num(start,end) {
 
 return Math.floor(start + (end - start) * Math.random());
 
}
 
console.log(random_int_num(10,100)); //69 随机

希望本文所述对大家JavaScript程序设计有所帮助。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们