JavaScript增量字符串上的一元运算符(++)

时间:2016-10-12 13:56:12

标签: javascript specifications

我在Chromium版本53.0.2785.143基于Ubuntu构建,在Ubuntu 16.04(64位)上运行

根据ECMAScript® Language Specification,前缀增量运算符的计算方法如下:

Prefix Increment Operator evaluation steps

考虑到这一点,我无法解释这个结果:

++'1';
> Uncaught ReferenceError: Invalid left-hand side expression in prefix operation

当以下代码像魅力一样工作时:

var x = '1'; 
++x;
> 2

据我了解,在这两种情况下,第二步的前三个要点都是正确的,而对于++'1'情况,第四个子弹也是真的(但为什么?)和{{1}如果它是假的,不会引起任何错误。我是对的吗?

PS:Firefox抛出++x而不是SyntaxError: invalid increment operand

2 个答案:

答案 0 :(得分:10)

问题是,您的/// <summary> /// Copies the contents of input to output. Doesn't close either stream. /// </summary> public static void CopyStream(Stream input, Stream output) { byte[] buffer = new byte[8 * 1024]; int len; while ( (len = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); } } public static void WriteFile(string fileName, Stream inputStream) { string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (!path.EndsWith(@"\")) path += @"\"; if (File.Exists(Path.Combine(path, fileName))) File.Delete(Path.Combine(path, fileName)); using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.CreateNew, FileAccess.Write) { CopyStream(inputStream, fs); } inputStream.Close(); inputStream.Flush(); } 运算符隐式涉及赋值,并且您无法为字符串常量指定新值。注意

++
由于同样的原因,

也是错误的。

答案 1 :(得分:3)

据我了解,mysql_query("REPLACE INTO archive.table ($fields) VALUES ($values)"); while ($listing = mysql_fetch_assoc($listings)){ $fields = array_keys($listing); $fields = implode(', ', $fields); $fields = "$fields"; $values = array_values($listing); $values = implode(", ", $values); $values = mysql_real_escape_string($values); $values = str_replace("`","'",$values); $values = "'$values'"; mysql_query("REPLACE INTO archive.table ($fields) VALUES ($values)"); } 类似。

因此它适用于++,因为它会被评估为+= 1++x,但x+=1是一个字符串文字并且没有左侧值分配,因此失败