javascript - Variable introduction, quotation marks, plus sign usage issues
PHPz
PHPz 2017-05-18 10:59:41
0
4
627

There is something I don’t understand very well. This time I saw a piece of code that explains the problem very well:

function moveElement (elementID, final_x, final_y, interval) {
    var elem = document.getElementById(elementID);
    var xpos = parseInt(elem.style.left);
    var ypos = parseInt(elem.style.top);
    ......
    var repeat = "moveElement('"+ elementID +"',"+ final_x +","+ final_y +","+ interval +")";
    movement = setTimeout(repeat, interval)
}

I only have one question:

var repeat = "moveElement('"+ elementID +"',"+ final_x +","+ final_y +","+ interval +")";

In this paragraph, elementID, final_x, final_y, interval are the four parameters passed in, except for the first One is a string, and the last three are numbers.

The first thing I don't understand is why these parameters need to be added with quotes . The second thing I don't understand is what role the plus sign has. Another question is why does a string like elementID contain double quotes? Under what circumstances is this necessary?

Generally I think the plus sign is suitable for string splicing, but this is obviously not the case here. A pair of quotation marks is an independent space. What is the meaning of the plus sign wrapped in it?

PHPz
PHPz

学习是最好的投资!

reply all(4)
洪涛

1. The quotes are enclosed in commas
2.123456+"somestring"→"123456somestring"
3.elementId is a String type parameter, so add quotes

滿天的星座

The variable is finally converted to a string! Numbers + quotation marks change characters. If the parameter you need is a string instead of a number

漂亮男人

The string here is equivalent to the usage of eval in setTimeout, which refers to the code string you want to execute after delay milliseconds

世界只因有你

First of all, the plus sign here is indeed used for string splicing

var repeat = "moveElement('"+ elementID +"',"+ final_x +","+ final_y +","+ interval +")";
The result of

is

var repeat = "moveElement(elementID, final_x, final_y, interval)"

Just pass the string variable named repeat as a parameter to setTimeout, that is, after interval milliseconds, repeat will be executed

var repeat = "moveElement('"+ elementID +"',"+ final_x +","+ final_y +","+ interval +")";
movement = setTimeout(repeat, interval)

This is actually basically the same as

movement = setTimeout(function () {
    moveElement(elementID, final_x, final_y, interval)
}, interval)

This should be easier to understand, right?

However, there are still differences between these two methods. Generally, the method mentioned by the questioner is not recommended. For details, see window.setTimeout, Running string as function in javascript setTimeout?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template