从接手的烂摊儿中又学到了一点点,今天被后端报了一个bug,莫名多出了一列,经排查
d的值为空时
1、判断>=0,0没有加引号,结果返回true
<td class="green" v-if="item.d>= 0">+{{item.d}}%</td>
2、判断等于''时,也返回true
<td class="green" v-if="item.d>= 0">+{{item.d}}%</td>
导致多出一列,于是写了个小实例又验证了一番,JS是弱类型语言,判断前,应该对数值类型进行强转,(补基础-->)在JS中null,0,””,false,和 undefined 全部彼此相等(==)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<script>
function display(){
const obj = [
{"a":"23:45","b":"2.1", "c":"-0.27","d":"-1.68"},
{"a":"16:15","b":"2.26", "c":"1.01","d":"2.62"},
{"a":"16:00","b":"2.27", "c":"1.26","d":""}];
obj.forEach((item, index) => {
/**
if (item.d < 0) {
console.log(item.d); // -1.68
}
*/
if (item.d < '0') {
console.log(item.d); // -1.68 ''
}
if (item.d >= '0') {
console.log(item.d); // 2.62
}
if (item.week >= 0) {
console.log(item.d); // 2.62 ''
}
});
}
</script>
</head>
<body>
<h2>神奇的JS</h2>
<button type="button" onclick="display()">显示结果</button>
</body>
</html>