JavaScript返回
程序执行完成后返回values。
You've already met return values a number of times, although you may not have thought about them explicitly.
You've already met return values a number of times, although you may not have thought about them explicitly.
let myText = 'The weather is cold'; let newString = myText.replace('cold', 'warm'); console.log(newString); // Should print "The weather is warm" // the replace() string function takes a string, // replaces one substring with another, // and returns a new string with the replacement made
The replace() 函数is调用invoked on the myText string, and is passed two parameters, 传递2个参数:
1. the substring to find ('cold').
2. the string to replace it with ('warm').
一些函数不返回任何值。
function draw() { ctx.clearRect(0, 0, WIDTH, HEIGHT); for(let i = 0; i < 100; i++){ ctx.beginPath(); ctx.fillStyle = 'rgba(255,0,0,0,0.5)'; ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI); ctx.fill(); } }
Insides each loop iteration, three calls are made to the random() function, to generate random value for the current circle's x-coordinate, y-coordinate, and radius, respectively. The random() function takes one parameter -- a whole number -- and it returns a whole random number between 0 and that number. it looks like this:
This return value appears at the point the function was called, and the code continues.
input.onchange = function() { const num = parseFloat(input.value); if (isNaN(num)) { para.textContent = 'You need to enter a number!'; } else { para.textContent = num + ' squared is ' + squared(num) + '. ' + num + ' cubed is ' + cubed(num) + '. ' + num + ' factorial is ' + factorial(num) + '.'; } }
function mySandwich(param1, param2, callback) { console.log('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2); $('#sandwich').animate({ opacity: 0 }, 5000, function() { console.log('Animation complete!'); }); if (callback && typeof(callback) === "function") { callback(); } } mySandwich('ham', 'cheese', function() { console.log('Finished eating my sandwich.'); });
(callback && typeof(callback) === "function") && callback();
- Functions in-depth — a detailed guide covering more advanced functions-related information.
- Callback functions in JavaScript — a common JavaScript pattern is to pass a function into another function as an argument. It is then called inside the first function. This is a little beyond the scope of this course, but worth studying before too long.
阅读量: 478
发布于:
修改于:
发布于:
修改于: