温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JS中使用数组的示例分析

发布时间:2021-06-11 15:21:10 来源:亿速云 阅读:155 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关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 随机

关于“JS中使用数组的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI