For which function is best, most JavaScript experts recommend using the []operator, saying it is more efficient than
calling theArrayconstructor.
For maintainability, use []
To test in http://jsfiddle.net/
In Html
<div id="test1">var arr = new Array(5); The array size is 1</div>
<div id="test2">var arr = [5]; The array size is 1</div>
<div id="test3">var arr = new Array(2, 5); The array size is 2</div>
Css
.error {
background-color: red
}
.success {
background-color: green
}
JS
var arr1 = new Array(5);
if (arr1.length === 1){
$("#test1").addClass("error");
}
else{
$("#test1").addClass("success");
}
var arr2 = [5];
if (arr2.length !== 1){
$("#test2").addClass("error");
}
else{
$("#test2").addClass("success");
}
var arr3 = new Array(2,5);
if(arr3.length === 2)
$("#test3").addClass("success");
else
$("#test").addClass("error");
Creating Arrays from Strings
html
<section>
<div>Creating Arrays from Strings</div>
<div id="words"></div>
</section>
<section>
<div>Find if string "the quick brown fox jumped over the lazy dog" contains substring "jumped"</div>
<div id="result"></div>
</section>
js
var sentence = "the quick brown fox jumped over the lazy dog";
var words = sentence.split(" ");
words.forEach(function(word){
$("#words").append('<div>' + word + '</div>');
})
if(sentence.indexOf("jumped") >= 0){
$("#result").addClass("success").html("Find it");
}else{
$("#result").addClass("error").html("Not Find it");
}