Following code is working fine on firefox but throwing an error on chrome - SyntaxError: Unexpected token [
I'm expecting this code to append date in given div.
var output = document.getElementById('output');
var classes = ['history', 'biology', 'physics'];
var students = 90;
function getExamDate() {
return [20, ' March ', 2013, ' 9AM'];
}
var [date, month, year, time] = getExamDate();
output.innerHTML(date + month + year + time);
This kind of statement
var [date, month, year, time] = getExamDate();
is a destructuring assignment . It is part of ECMAScript 6. It's not yet available in most browsers.
For now, you'd better avoid assigning all those variables :
output.innerHTML = getExamDate().join('');
(yes, you had another error: innerHTML
is accessed as a property, not a function)
Here's a good introductory article on destructuring assignments .
You are using ECMAScript 6
feature called Array destructuring
which is not a standard yet. Only modern browsers like chrome and firefox have implemented some of the features. Array destructuring is useful shorthand when returning multiple values from a function, as we do not need to wrap around an object anymore.
In your case you can tweak your code to return a simple array instead, as shown below in following code snippet.
I have used isNumber
function to check if array item is number. If it's a string then remove quotes around it. You will end you with exactly same output.
var output = document.getElementById('output');
var classes = ['history', 'biology', 'physics'];
var students = 90;
function getExamDate() {
return [20, ' March ', 2013, ' 9AM'];
}
var temp = getExamDate();
for(var i = 0; i < temp.length; i++) {
var str = temp[i];
if(!isNumber(str)) {
str = str.replace(/"/g, '');
}
console.log(str);
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
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.