I have this code:
if (Array.length === maxArrayLength) {
alert("test1234");
Array= [];
}
which should display a message when the array Array
has a length eequal to the variable maxArrayLength
, but instead, it does nothing.
But if I replace the maxArrayLength
with 2
or a different number, it works.
There is a value in maxArrayLength
, because when I do console.log(maxArrayLength);
before (and after) the if
statement, I get a value.
If it helps, this is in a Chrome Extension. The maxArrayLength
is from chrome.local.storage
:
chrome.storage.sync.get('maxArray', function (items) {
maxArray = items.maxArrayLength;
console.log(maxArrayLength);
});
The console.log
over here also works. I'm stumped. What's wrong? It's as if the if
statement can't access the maxArrayLength
variable...?
Check the typeof(maxArrayLength)
against the typeof(Array.length)
.
By using ===
you're saying not only should the values be the same but also the data types.
For example:
"3" == 3 // true
"3" === 3 // false
If I understand your problem correctly then, you just want compare value of variable maxArrayLength with Array.length so use == operator instead ===.
eg
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create an array, then check it's length.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var maxArrayLength= 4;
if (fruits.length == maxArrayLength){
alert("Array length equals maxArrayLength");
}
}
</script>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.