Get the index of the character "x" in the part to distinguish between parts that have it like "3x", "x^11", ... and parts that doesn't like "+5", ... var power = ...:如果部件(x === -1)中没有"x",则该部件的功效为0.If there isn't an "x" in the part (x === -1) then the power of this part is 0.否则(存在"x"),然后我们检查"x"(part[x + 1])之后的字符是否为"^",如果是,则幂是其后的任意数字(将其切掉)字符串part.slice(x + 2)的一部分,并使用一元+将其转换为数字),如果"x"之后没有"^",则幂为1.Otherwise (an "x" is present), then we check if the character right after "x" (part[x + 1]) is "^", if it is then the power is whaterver number that comes after it (cut that bit of the string part.slice(x + 2) and cast it to number using unary +), if there isn't a "^" after "x", then the power is 1. res[power] = (res[power] || 0) + coef;:将刚刚计算出的系数coef添加到该功率的已累积系数中(如果没有累积,则使用0).Add the coeficient coef that has just been calculated to the already accumulated coeficient of this power (if nothing is accumulated then use 0).此行可以这样简化:if(res[power]) // if we already encountered this power in other parts before res[power] += coef; // then add this coeficient to the sum of those previous coeficientselse // otherwise res[power] = coef; // start a new sum initialized with this coeficient这使得在相同的字符串中多次包含相同的幂成为可能,例如:"5x + 10x + 1 + x",... this makes it possible to include the same power more than one time in the same string like: "5x + 10x + 1 + x", ... 将生成的对象转换为所需的数组: 因此:{ "3": 7, "0": 19}将是:[7, 0, 0, 19] var ret = { "3": 7, "0": 19 }; // the returned objectvar powers = Object.keys(ret); // get all the powers (in this case [3, 0])var max = Math.max.apply(null, powers); // get the max power from powers array (in this case 3)var result = [];for(var i = max; i >= 0; i--) // from the max power to 0 result.push(ret[i] || 0); // if that power has a coeficient then push it, otherwise push 0 console.log(result); 这篇关于获取代数项系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-30 03:12