4 數(shù)組和對象
在JS中創(chuàng)建數(shù)組非常簡單. 直接[ ]即可. 也可以用正規(guī)軍的new Array(). 不過效果都是一樣的.
var as = [11,22,33,44,55];
var bs = new Array(11,22,33,44,55);
數(shù)組的常用操作:
arr.length; // 數(shù)組長度
arr.push(data); // 添加數(shù)據(jù)
arr.pop(); // 刪除數(shù)據(jù), 從后面刪除, 并返回被刪除的內(nèi)容
arr.shift() // 刪除數(shù)據(jù), 從前面刪除, 并返回被刪除的內(nèi)容
// arr中的每一項循環(huán)出來. 分別去調(diào)用function函數(shù), 會自動的將`數(shù)據(jù)`傳遞給函數(shù)的第一個參數(shù)
arr.forEach(function(e, i){ // 第二個參數(shù)是可選的
console.log(i+"__"+e);
});
arr.join("連接符"); // 使用`連接符`將arr中的每一項拼接起來. 和python中的 "".join()雷同
在JS中創(chuàng)建一個對象非常容易. 和python中的字典幾乎一樣{ }:
var p = {
name: "wf",
age: 18,
wife: "zzy",
chi: function(){
console.log("吃飯")
}
};
使用對象
p.name
p.age
p['wife']
p.chi()
p['chi']()
從上述內(nèi)容中幾乎可以看到. JS對象的使用幾乎是沒有門檻的. 十分靈活文章來源:http://www.zghlxwxcb.cn/news/detail-655479.html
for(var n in p){
if(typeof(p[n]) != 'function'){
console.log(p[n])
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>數(shù)組和對象</title>
</head>
<body>
<script src = "數(shù)組和對象.js"></script>
</body>
</html>
// // 數(shù)組的常用操作
var arr = [11, 22, 33, 44, 55, 66];
// 數(shù)組的長度
console.log(arr.length);
// 數(shù)組中添加數(shù)據(jù)
arr.push(77)
// 數(shù)組中刪除數(shù)據(jù),從后面刪除并返回刪除的內(nèi)容
console.log(arr.pop());
// 數(shù)組中刪除數(shù)據(jù),從前面刪除并返回刪除的內(nèi)容
console.log(arr.shift());
// arr.forEach(function(e, i){ // 第二個參數(shù)是可選的
arr.forEach(function(e){ // 第二個參數(shù)是可選的
console.log(e);
});
// python中的 "".join()雷同
console.log(arr.join('|'));
var p = {
name: 'wf',
age: 20,
wife: 'zzy',
chi:function () {
console.log("吃飯")
}
}
console.log(p.name);
console.log(p.age);
console.log(p.wife);
console.log(p.chi());
console.log(p['chi']());
for (var n in p){
if (typeof (p[n]) != 'function'){
console.log(p[n]);
}
}
代碼的效果圖如下:
文章來源地址http://www.zghlxwxcb.cn/news/detail-655479.html
到了這里,關(guān)于4 JavaScript數(shù)組和對象的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!