js對象獲取屬性有兩種方法:1.通過.的方式 2. 通過[]方式
// 通過.方式獲取屬性值,key是靜態的 var aa = {name: "zhang", age: 18}; console.log(aa.name); // 通過[]獲取屬性值, key是動態的,可以是字符串,或者數字的形式 var bb = {"apple": 3, "pear": 2} var cc = {1: "number1", 2: "number2"} console.log(bb["apple"]); console.log(cc[1]); // 注意這里的寫法跟數組容易混淆,cc仍是對象,不是數組 // 獲取對象所有key的方法 console.log(Object.keys(bb)); // 輸出[ 'apple', 'pear' ]
那什么是靜態什么是動態?
前言:
今天封裝了一個函數,發現寫的時候用 [ ] 就可以, . 就不可以,就覺得非常奇怪,后來查看了一些大佬的技術博客之后,終於弄懂了這個問題,下面我跟大家分享一下。
代碼:獲取任意一個元素的任意屬性
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 100px;
height: 100px;
background: pink;
/* position: absolute; */
left: 100px;
top:50px;
}
</style>
<body>
<input type="button" value="按鈕" id="btn">
<div id="box"></div>
<script>
var box = document.getElementById('box');
function getStyle(element,attr){
if(window.getComputedStyle){
return window.getComputedStyle(element,null)[attr];
}else{
return element.currentStyle[attr];
}
}
document.getElementById('btn').onclick=function(){
// console.log(box.offsetLeft)
console.log(getStyle(box,'top')); //50px,是一個字符串類型
}
</script>
</body>
注意: 以上代碼若將[attr]換成.attr就獲取不到了,原因就是
通過.方式獲取屬性值,key是靜態的,
通過[]獲取屬性值, key是動態的,可以是字符串,或者數字的形式,那這里的attr是我傳的參數,值是可變的,當然就不可以用.的方式獲取屬性值啦~小伙伴們不要采坑哦!
